package com.qijian.mold.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.exception.ServiceException;
import com.qijian.mold.domain.entity.MoldChangeLog;
import com.qijian.mold.domain.vo.moldChangeLog.ChangeLogListVo;
import com.qijian.mold.enums.MoldChangeLogDetailsTypesEnum;
import com.qijian.mold.enums.MoldChangeLogTypesEnum;
import com.qijian.mold.repository.MoldChangeLogRepository;
import com.qijian.mold.service.MoldChangeLogService;
import com.qijian.mold.util.IdGenerator;
import com.qijian.system.mapper.SysUserMapper;
import com.qijian.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 换模进展日志信息
 *
 * @author anni.zhu
 * @author anni.zhu@king-v.com
 * Created in 2025/3/29 17:25
 */
@Service
public class MoldChangeLogServiceImpl implements MoldChangeLogService {
    @Autowired
    private MoldChangeLogRepository logRepository;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public void saveChangeLog(Long moldChangeId, Long operatorId, MoldChangeLogTypesEnum type, MoldChangeLogDetailsTypesEnum detailsType, List<Long> confirmUserIds) {
        MoldChangeLog moldChangeLog = new MoldChangeLog();
        moldChangeLog.setMoldChangeId(moldChangeId);
        moldChangeLog.setOperatorId(operatorId);
        moldChangeLog.setLogType(type.getId());
        if (detailsType!=null){
            moldChangeLog.setDetailsType(detailsType.getId());
        }else{
            moldChangeLog.setDetailsType(MoldChangeLogDetailsTypesEnum.DEFAULT.getId());
        }
        String confirmUser = JSONArray.toJSONString(confirmUserIds);
        moldChangeLog.setConfirmUserIds(confirmUser);
        moldChangeLog.setId(IdGenerator.SNOW.generate());
        if (!logRepository.save(moldChangeLog)) {
            throw new ServiceException("新增换模进展日志失败");
        }
    }

    @Override
    public void saveTaskLog(Long taskId, Long moldChangeId, Long operatorId, MoldChangeLogDetailsTypesEnum detailsType, Long confirmUserId) {
        MoldChangeLog moldChangeLog = new MoldChangeLog();
        moldChangeLog.setMoldChangeId(moldChangeId);
        moldChangeLog.setOperatorId(operatorId);
        moldChangeLog.setMoldTaskId(taskId);
        moldChangeLog.setLogType(MoldChangeLogTypesEnum.MOLD_CHANGE_DEBUG.getId());
        moldChangeLog.setDetailsType(detailsType.getId());

        List<Long> confirmUserIds = new ArrayList<>();
        if (confirmUserId != null) {
            confirmUserIds.add(confirmUserId);
        }
        String confirmUser = JSONArray.toJSONString(confirmUserIds);
        moldChangeLog.setConfirmUserIds(confirmUser);
        moldChangeLog.setId(IdGenerator.SNOW.generate());
        if (!logRepository.save(moldChangeLog)) {
            throw new ServiceException("新增换模进展日志失败");
        }
    }


    /**
     * 根据换模单id获取进展日志列表
     *
     * @param moldChangeId
     * @return
     */
    @Override
    public List<ChangeLogListVo> getChangeLogList(Long moldChangeId) {
        List<ChangeLogListVo> changeLogListVos = new ArrayList<>();

        List<MoldChangeLog> moldChangeLogs = logRepository.getBaseMapper().selectList(
                new LambdaQueryWrapper<>(MoldChangeLog.class)
                        .eq(MoldChangeLog::getMoldChangeId, moldChangeId)
                        .eq(MoldChangeLog::getIsDel, 0)
                        .orderByAsc(MoldChangeLog::getCreateTime)
        );

        if (CollectionUtil.isNotEmpty(moldChangeLogs)){
            for (MoldChangeLog moldChangeLog : moldChangeLogs) {
                ChangeLogListVo vo=new ChangeLogListVo();
                BeanUtils.copyProperties(moldChangeLog, vo);
                List<Long> ids = JSONArray.parseArray(moldChangeLog.getConfirmUserIds(), Long.class);
                //获取确认人信息
                if (CollectionUtil.isNotEmpty(ids)){
//                    List<SysUser> userList = getUserList(ids);
//                    if (CollectionUtil.isNotEmpty(userList)){
//                        List<String> nameList = userList.stream().map(SysUser::getUserName).collect(Collectors.toList());
//                        vo.setConfirmUserList(nameList);
//                    }
                    List<String> idList=new ArrayList<>();
                    for (Long id : ids) {
                        idList.add(id.toString());
                    }
                    vo.setConfirmUserList(idList);
                }

                List<Long> visibleUserIds = JSONArray.parseArray(moldChangeLog.getVisibleUserIds(), Long.class);
                if (CollectionUtil.isNotEmpty(visibleUserIds)){
                    List<String> idList=new ArrayList<>();
                    for (Long id : visibleUserIds) {
                        idList.add(id.toString());
                    }
                    vo.setVisibleUserList(idList);
                }
                changeLogListVos.add(vo);
            }
        }
        return changeLogListVos;
    }

    @Override
    public MoldChangeLog getLastChangeLog(Long moldChangeId) {
        MoldChangeLog log=new MoldChangeLog();
        List<MoldChangeLog> moldChangeLogs = logRepository.getBaseMapper().selectList(
                new LambdaQueryWrapper<>(MoldChangeLog.class)
                        .eq(MoldChangeLog::getMoldChangeId, moldChangeId)
                        .eq(MoldChangeLog::getIsDel, 0)
                        .orderByDesc(MoldChangeLog::getCreateTime)
        );
        if (CollectionUtil.isNotEmpty(moldChangeLogs)){
            log=moldChangeLogs.get(0);
        }
        return log;
    }

    @Override
    public void removeLogByChangeId(Long moldChangeId) {
        List<MoldChangeLog> moldChangeLogs = logRepository.getBaseMapper().selectList(
                new LambdaQueryWrapper<>(MoldChangeLog.class)
                        .eq(MoldChangeLog::getMoldChangeId, moldChangeId)
                        .eq(MoldChangeLog::getIsDel, 0)

        );
        if (CollectionUtil.isNotEmpty(moldChangeLogs)){
            List<Long> ids = moldChangeLogs.stream().map(MoldChangeLog::getId).distinct().collect(Collectors.toList());
            if (!logRepository.removeByIds(ids)){
                throw new ServiceException("删除换模进展日志失败");
            }
        }
    }

    @Override
    public void removeLogByTaskId(Long taskId) {
        List<MoldChangeLog> moldChangeLogs = logRepository.getBaseMapper().selectList(
                new LambdaQueryWrapper<>(MoldChangeLog.class)
                        .eq(MoldChangeLog::getMoldTaskId, taskId)
                        .eq(MoldChangeLog::getIsDel, 0)

        );
        if (CollectionUtil.isNotEmpty(moldChangeLogs)){
            List<Long> ids = moldChangeLogs.stream().map(MoldChangeLog::getId).distinct().collect(Collectors.toList());
            if (!logRepository.removeByIds(ids)){
                throw new ServiceException("删除换模进展日志失败");
            }
        }
    }

    @Override
    public void update(MoldChangeLog moldChangeLog) {
        if (moldChangeLog.getId() == null) {
            throw new ServiceException("日志id不能为空");
        }
        if (!logRepository.updateById(moldChangeLog)) {
            throw new ServiceException("修改换模进展日志失败");
        }
    }

    List<SysUser> getUserList(List<Long> ids) {
      List<SysUser> sysUsers =new ArrayList<>();
        if (CollectionUtil.isNotEmpty(ids)){
            for (Long id : ids) {
                SysUser sysUser = sysUserMapper.selectUserById(id);
                if (sysUser!=null){
                    sysUsers.add(sysUser);
                }
            }
        }
        return sysUsers;
    }
}
